package com.huika.dealontop.control.main;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.base.BaseFra;
import com.huika.dealontop.control.base.BaseFra.FragmentKeyDown;
import com.huika.dealontop.control.homepage.fragment.HomePageFragment;
import com.huika.dealontop.control.myinfo.fragment.MyInfoFragment;
import com.huika.dealontop.control.nearby.fragment.NearbyFragment;
import com.huika.dealontop.control.timelimit.fragment.ShoppingCartFragment;
import com.huika.dealontop.support.event.CallMainPagerChangeEvent;
import com.huika.dealontop.support.event.SelectLanguageEvent;
import com.huika.dealontop.support.event.SelectNearByEvent;
import com.huika.dealontop.support.event.SelectShoppingCarEvent;
import com.huika.dealontop.utils.SelectLanguageUtils;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.utils.VersionManager;
import com.huika.dealontop.views.JazzyViewPager;
import com.huika.dealontop.views.JazzyViewPager.TransitionEffect;

import java.util.HashSet;
import java.util.Set;

import cn.sharesdk.framework.ShareSDK;
import de.greenrobot.event.EventBus;

public class MainActivity extends BaseAct implements ViewPager.OnPageChangeListener {

    public JazzyViewPager pager;
    private LinearLayout page_indicator;
    private Set<Integer> initFrags;
    private MainPagerAdapter pagerAdapter;
    private VersionManager versionManager;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    isExit = false;
                    break;
                case 1:
                    versionManager.checkVersion(false, true, mHandler);
                    break;
            }
        }

        ;
    };
    /**
     * 是否退出应用
     */
    private boolean isExit;
    private static TextView mCartProductNumber;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Object instantiateItem = pagerAdapter.instantiateItem(pager, pager.getCurrentItem());
        if (instantiateItem instanceof FragmentKeyDown) {
            FragmentKeyDown iFraKeyDown = (FragmentKeyDown) instantiateItem;
            if (iFraKeyDown.onFraKeyDown(keyCode, event))
                return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                showToastMsg(getString(R.string.frame_exit));
                isExit = true;
                mHandler.sendEmptyMessageDelayed(0, 1000);
                return true;
            } else {
                // sendBroadcast(new Intent(Constant.ACTION_EXIT_SYSTEM));
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    ;

    @Override
    public void setRootView() {
        SelectLanguageUtils.setLanguage(this);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
    }

    public void onEventMainThread(SelectLanguageEvent event) {
        this.finish();
    }


    /**
     * 用EventBus，通知主页切换界面
     */
    public void onEventMainThread(CallMainPagerChangeEvent event) {
        pager.setCurrentItem(event.changePageNo, false);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (intent != null) {
            int pageNum = intent.getIntExtra(Constants.NAVIGATION_FLAG, -1);
            pager.setCurrentItem(pageNum, false);
        }

    }

    @Override
    protected void initWidget() {
        super.initWidget();

//        Log.d("TAG","=====城市===================="+ new GMapUtil().getCurrentCity());

        //初始化sharpSdk
        ShareSDK.initSDK(this);
//        new GMapUtil(this).requestGMapLocation();

        pager = (JazzyViewPager) findViewById(R.id.pager);
        pager.setFadeEnabled(true);
        pager.setPagingEnabled(false);
        pager.setTransitionEffect(TransitionEffect.Standard);

        pager.setOffscreenPageLimit(4);

        pager.setOnPageChangeListener(this);
        pagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
        // pagerAdapter = new MainPagerAdapter();
        pager.setAdapter(pagerAdapter);
        mCartProductNumber = (TextView) findViewById(R.id.main_cartProductNumber);
        page_indicator = (LinearLayout) findViewById(R.id.page_indicator);
        int tabCount = page_indicator.getChildCount();
        for (int i = 0; i < tabCount; i++) {
            page_indicator.getChildAt(i).setTag(i);
            page_indicator.getChildAt(i).setOnClickListener(this);
        }

        initFrags = new HashSet<Integer>();
        initFrags.add(0);
        onPageSelected(0);


        versionManager = new VersionManager(this);
        versionManager.checkVersion(false, false, mHandler);


    }

    //此方法直接使用HomePageFragment的广播来调用。
    public static void initCartProduct(int cartProductNumber) {
        if (mCartProductNumber == null) {
            return;
        }

        if (cartProductNumber == 0) {
            mCartProductNumber.setVisibility(View.INVISIBLE);
        } else {
            mCartProductNumber.setText(cartProductNumber + "");
            mCartProductNumber.setVisibility(View.VISIBLE);
        }
    }
    private NearbyFragment mnearbyFragment;

    public void setNearByTransfer(int nearByValueId) {
        if (mnearbyFragment != null) {
            mnearbyFragment.setSelectedId(nearByValueId);
        }
    }

    private class MainPagerAdapter extends FragmentStatePagerAdapter {

        public MainPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment frag = null;
            switch (position) {
                case 0:
                    frag = new HomePageFragment();
                    break;
                case 1:
                    mnearbyFragment = new NearbyFragment();
                    frag = mnearbyFragment;

                    break;
                case 2:
//                    frag = new TimeLimitFragment();
                    frag = new ShoppingCartFragment();
                    break;
                case 3:
                    frag = new MyInfoFragment();
                    break;
            }
            return frag;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Object object = super.instantiateItem(container, position);
            pager.setObjectForPosition(object, position);
            return object;
        }

        @Override
        public int getCount() {
            return 4;
        }

    }

    private int item1 = -1;

    /**
     * viewpager监听
     **************************/
    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int item) {
        this.item1 = item;
        if(item!=2){
            mCartProductNumber.setBackgroundResource(R.drawable.icon_cart_count_bg);
        }else{
            mCartProductNumber.setBackgroundResource(R.drawable.mainactivity_cartproduct);
        }
        mCartProductNumber.setPadding(UIUtils.dip2px(1), UIUtils.dip2px(1), UIUtils.dip2px(1), UIUtils.dip2px(1));
        final int tabCount = page_indicator.getChildCount();
        for (int i = 0; i < tabCount; i++) {
            final View child = page_indicator.getChildAt(i);
            final boolean isSelected = (i == item);
            child.setSelected(isSelected);
        }

        if (!initFrags.contains(item)) {
            initFrags.add(item);
            Object frag = pagerAdapter.instantiateItem(pager, item);
            if (frag instanceof BaseFra.OnInitShowListener) {
                ((BaseFra.OnInitShowListener) frag).onInitShow();
            }
        } else {
            if (item == 4) {
                Object frag = pagerAdapter.instantiateItem(pager, item);
                if (frag instanceof BaseFra.OnInitShowListener) {
                    ((BaseFra.OnInitShowListener) frag).onInitShow();
                }
            }
        }

    }




    /** viewpager监听 end **************************/

    /**
     * 只针对tab
     */
    @Override
    public void widgetClick(View v) {
        int index = (Integer) v.getTag();
        if (index == 2 && item1 == index) {
            EventBus.getDefault().post(new SelectShoppingCarEvent("ShoppingCart"));
        } else if (index == 1 && item1 == index) {
            EventBus.getDefault().post(new SelectNearByEvent("NearBy"));
        }
        if (index != pager.getCurrentItem()) {
            pager.setCurrentItem(index, false);
        }
        super.widgetClick(v);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


}
